package org.mcache.test;

import org.junit.Test;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;

/**
 * @Author: tjc
 * @description
 * @Date Created in 21:40 2022-10-01
 * A client sends the Redis server a RESP Array consisting of only Bulk Strings.
 */
public class CommandToServer {

    // SET key value -> *3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n
    public static String convertRESP(String str) {
        List<String> words = new LinkedList<>();
        for (int start = 0; start < str.length(); ) {
            int i = notBlankFrom(str, start);
            int j = nextBlankFrom(str, i);
            words.add(str.substring(i, j));
            start = j;
        }

        List<String> blukWords = words.stream().map(CommandToServer::blukStr).collect(Collectors.toList());

        return recpArray(blukWords);
    }

    public static int notBlankFrom(String str, int from) {
        if (from < 0)
            throw new IllegalArgumentException();
        int i = from;
        for (; i < str.length(); i++) {
            char c = str.charAt(i);
            if (blank(c)) {
                continue;
            }
            break;
        }
        return i;
    }

    private static boolean blank(char c) {
        return c == '\t' || c == ' ';
    }


    private static int nextBlankFrom(String str, int from) {
        if (from < 0)
            throw new IllegalArgumentException();
        int i = from;
        for (; i < str.length(); i++) {
            char c = str.charAt(i);
            if (blank(c)) {
                return i;
            }
        }
        return i;
    }

    public static String recpArray(Collection<String> str) {
        StringBuffer tmp = new StringBuffer("*" + str.size() + "\r\n");
        for (String s : str) {
            tmp.append(s);
        }
        return tmp.toString();
    }

    public static String blukStr(String str) {
        return "$" + str.length() + "\r\n" + str + "\r\n";
    }

    @Test
    public void test1() {
        String cmd = "SET key value";
        String result = convertRESP(cmd);
        assertEquals(result, "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n");
    }

    @Test
    public void test2() {
        String cmd = "SET key value";
        convertRESP(cmd);
    }
}
